package com.itany.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Author：汤小洋
 * Date：2022-11-11 9:16
 * Description：<描述>
 */
@WebFilter("/index.jsp")
public class PageFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
        // 1.获取到客户端的地址
        String addr = req.getRemoteAddr();
        // 2.然后到application中查找是否已存在
        ServletContext application = req.getServletContext();
        Object obj = application.getAttribute(addr);
        if(obj == null){
            application.setAttribute(addr,addr);
            filterChain.doFilter(req,res);
        }else{ // 不是第一次访问
            HttpServletResponse resp = (HttpServletResponse) res;
            HttpServletRequest request = (HttpServletRequest) req;
            resp.sendRedirect(request.getContextPath()+"/fail.jsp");
        }

    }

    @Override
    public void destroy() {

    }
}
